﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using JESAI.Core.Util.Extensions.Strings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Core.Http
{
    public class HttpRequestQueryParams
    {
        public static async Task<Dictionary<string, string>> QueryParameters(HttpContext context)
        {
            var request = context.Request;
            request.EnableBuffering();
            if (request.Body.CanSeek)
            {
                request.Body.Seek(0, SeekOrigin.Begin);
            }
            var parameters = new Dictionary<string, string>();
            // 解析请求头中的 Content-Type
            var contentType = request.ContentType;
            if (contentType.IsNullOrEmptyOrWhiteSpace())
            {
                contentType = "none";
            }
            // 根据 Content-Type 类型进行不同的参数解析
            if (HttpMethods.IsPost(request.Method) && (contentType.Contains("application/x-www-form-urlencoded")))
            {
                // 针对 Content-Type 为 application/x-www-form-urlencoded 的 Form 表单提交参数，使用 FormCollection 类型接收
                var form = await context.Request.ReadFormAsync();
                foreach (var key in form.Keys)
                {
                    parameters[key] = form[key];
                }
            }
            else if (HttpMethods.IsPost(request.Method) && contentType.Contains("multipart/form-data"))
            {
                // 针对 Content-Type 为 multipart/form-data 的 Form 表单提交参数，使用 IFormFileCollection 和 FormCollection 类型接收
                var form = await request.ReadFormAsync();
                foreach (var key in form.Keys)
                {
                    parameters[key] = form[key];
                }
                var files = form.Files;
                var fileIndex = 0;
                foreach (var file in files)
                {
                    parameters["file_" + fileIndex] = $"FileName:" + file.FileName + ",Name:" + file.Name + ",Length:" + file.Length;
                    // 保存上传的文件数据到磁盘或内存中
                }
            }
            else if (HttpMethods.IsPost(request.Method) && contentType.Contains("application/json"))
            {
                // 针对 Content-Type 为 application/json 的 JSON 格式请求参数，使用 StreamReader 类型接收
                using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))
                {
                    var body = await reader.ReadToEndAsync();
                    parameters["JsonData"] = body;
                }
            }
            else if (HttpMethods.IsPost(request.Method) && contentType.Contains("text/xml"))
            {
                // 针对 Content-Type 为 text/xml 的 XML 格式请求参数，使用 StreamReader 类型接收
                using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))
                {
                    var body = await reader.ReadToEndAsync();
                    parameters["XmlData"] = body;
                }
            }
            else if (HttpMethods.IsPut(request.Method) || HttpMethods.IsDelete(request.Method) || HttpMethods.IsOptions(request.Method) || HttpMethods.IsHead(request.Method))
            {
                // 针对 PUT、DELETE、OPTIONS、HEAD 等请求类型，使用 HeaderDictionary 类型接收
                var headers = request.Headers;
                foreach (var key in headers.Keys)
                {
                    parameters[key] = headers[key];
                }
                // 使用 StreamReader 类型接收请求体数据
                using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))
                {
                    var body = await reader.ReadToEndAsync();
                    parameters["Body"] = body;
                }
            }
            //此类数据流，不处理
            else if ((contentType != null && contentType.Contains("application/octet-stream")) || (contentType != null && contentType.Contains("application/octet-stream")))
            {
                // 针对 Content-Type 为 application/octet-stream 或者其他自定义的 MIME 类型的请求，使用 StreamReader 类型接收请求体数据

                //using (StreamReader reader = new StreamReader(context.Request.Body))
                //{
                //    var body = await reader.ReadToEndAsync();
                //    parameters["Data"] = body;
                //}
            }
            else
            {
                // 针对 GET 请求参数，使用 QueryCollection 类型接收
                var query = request.Query;
                foreach (var key in query.Keys)
                {
                    parameters[key] = query[key];
                }
            }
            if (request.Body.CanSeek)
            {
                request.Body.Position = 0;
                request.Body.Seek(0, SeekOrigin.Begin);
            }
            return parameters;
        }
    }
}
